<?php
namespace app\admin\controller;

use think\Loader;
use think\Request;
use app\common\controller\Base;
use app\common\model\Friend as FriendModel;

class Friend extends Base
{
    public function index(){

        $friends = FriendModel::order('id desc')->paginate(20);

        return view('',['friends'=>$friends]);
    }

    public function add(){


        return view();
    }


    public function edit(Request $request){

        $id = $request ->param('id');

        $friend = FriendModel::find($id);

        return view('',['friend'=>$friend]);
    }

    public function create(Request $request){
        if(!$request->isPost()){
            $this->error("来源非法");
        }
        $data = $request->only(['name','cover','url']);

        $validate = Loader::validate('FriendValidate');
        $result = $validate -> scene('add')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        $friendModel = new FriendModel();
        $friendModel->save($data);

        $this->success("添加成功");

    }

    public function update(Request $request){
        if(!$request->isPost()){
            $this->error("非法来源");
        }

        $id = $request->param('id',0,'intval');
        if(!$id){
            $this->error("非法来源");
        }

        $data = $request->only(['name','cover','url']);

        $validate = Loader::validate('FriendValidate');
        $result = $validate -> scene('edit')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        $friend = FriendModel::find($id);
        if(!$friend) {
            $this->error('不存在该条目');
        }

        $friend->save($data);
        $this->success("更新成功");

    }

    public function delete(Request $request){
        if(!$request->isDelete()){
            $this->error("非法来源");
        }
        $id = $request->param('id',0,'intval');
        if(!$id){
            $this->error("非法来源");
        }
        $res = FriendModel::destroy($id);
        if($res){
            $this->success("删除成功");
        }
        $this->error("删除失败");
    }


}
